﻿// Copyright (c) 2014 Jonathan Magnan (http://jonathanmagnan.com/).
// All rights reserved (http://zzzproject.com/sqlbulkcopy-extensions/).
// Licensed under MIT License (MIT) (https://zsqlbulkcopy.codeplex.com/license/).
using System;
using System.Collections.Generic;
using System.Text;

namespace Z.Net.Extensions
{
    internal partial class SqlBulkOperation
    {
        /// <summary>
        ///     Create the temporary table.
        /// </summary>
        public void CreateTemporaryTable()
        {
            string tableName = TemporaryTableName;
            List<string> list = Setting.TableColumns;

            var sb = new StringBuilder();
            sb.AppendLine("CREATE TABLE " + tableName);
            sb.AppendLine("(");
            if (Setting.IsSqlAzure)
            {
                // TODO: Remove identity for performance issue?
                sb.AppendLine("[8FEF2341_951C_47B6_BF7E_D350E54FFE4D] INT IDENTITY(1, 1), ");
            }

            sb.AppendLine(string.Join("," + Environment.NewLine, list.ToArray()));

            // Add default value to custom column
            if (SqlBulkCopy.BatchSize > 0)
            {
                sb.AppendLine(string.Concat(", ", "[", TemporaryColumnName, "] INT NULL"));
            }

            sb.AppendLine(Setting.IsSqlAzure ? " CONSTRAINT [PK_8FEF2341_951C_47B6_BF7E_D350E54FFE4D] PRIMARY KEY CLUSTERED ( [8FEF2341_951C_47B6_BF7E_D350E54FFE4D] ASC) )" : ")");

            CreateTemporaryTable(sb.ToString());
        }
    }
}